package com.yangqi;

import com.yangqi.io.User;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class saveUser {

    public static List<User> read(String path) {
        File file = new File(path);
        if (file.exists() && file.isFile()) {
            ObjectInputStream objectInputStream = null;
            try {
                InputStream inputStream = Files.newInputStream(Paths.get(path));
                objectInputStream = new ObjectInputStream(inputStream);

                List<User> users = new ArrayList<>();
                while (inputStream.available() > 0) {
                    Object o = objectInputStream.readObject();
                    if (o != null) {
                        users.add(((User) o));
                    } else {
                        break;
                    }
                }
                System.out.println(users.toString());
            } catch (IOException | ClassNotFoundException e) {
                throw new RuntimeException(e);
            } finally {

                try {
                    if (objectInputStream != null) {
                        objectInputStream.close();
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        } else {
            throw new RuntimeException("文件不存在");
        }
        return null;
    }

    public static void write() {
        List<User> list = new ArrayList<>();
        User user1 = new User(1, "小明", 2, "西安", false);
        User user2 = new User(1, "小陈", 2, "西安", false);
        User user3 = new User(1, "小段", 2, "西安", false);
        list.add(user1);
        list.add(user2);
        list.add(user3);
        String path = "D:\\home\\cache\\user.object";

        try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(Paths.get(path)));
             ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(Paths.get(path)))
        ) {
            for (User item : list) {
                oos.writeObject(item);
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //将以下User类的对象 user1,user2,user3，并且存储到 user.object 文件中
    public static void main(String[] args) {
        String path = "D:\\home\\cache\\user.object";

//        write();
        read(path);
    }


}
